/**
 * 
 */
package gui.util;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/**
 * Provides filtering based on file extension to the file chooser.
 * 
 * Note: Example taken from http://www.java2s.com/Code/JavaAPI/javax.swing/JFileChoosersetFileFilterFileFilterfilter.htm
 */
public class ExtensionFileFilter extends FileFilter {
	String m_description;

	String m_extensions[];

	public ExtensionFileFilter(String description, String extension) {
		this(description, new String[] { extension });
	}

	public ExtensionFileFilter(String description, String extensions[]) {
		if (description == null) {
			this.m_description = extensions[0];
		} else {
			this.m_description = description;
		}
		this.m_extensions = (String[]) extensions.clone();
		toLower(this.m_extensions);
	}

	private void toLower(String array[]) {
		for (int i = 0, n = array.length; i < n; i++) {
			array[i] = array[i].toLowerCase();
		}
	}

	/* (non-Javadoc)
	 * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
	 */
	@Override
	public boolean accept(File file) {
		if (file.isDirectory()) {
			return true;
		} else {
			String path = file.getAbsolutePath().toLowerCase();
			for (int i = 0, n = m_extensions.length; i < n; i++) {
				String extension = m_extensions[i];
				if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
					return true;
				}
			}
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see javax.swing.filechooser.FileFilter#getDescription()
	 */
	@Override
	public String getDescription() {
		return m_description;
	}

}
